package com.yuanfeng.biz.admin.admin.web;

import com.yuanfeng.entity.Admins;
import com.yuanfeng.util.BaseServlet;
import com.yuanfeng.util.MD5Util;
import com.yuanfeng.biz.admin.admin.service.AdminService;
import com.yuanfeng.biz.admin.admin.service.AdminServiceImpl;
import com.yuanfeng.util.WebUtil;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AdminServlet extends BaseServlet {
	AdminService service = new AdminServiceImpl();

	/**
	 * 管理员登陆
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void login(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Admins admin = WebUtil.copyRequestToBean(request, Admins.class);
		Admins loginAdmin = service.login(admin.getName());
		if(loginAdmin!=null){
			System.out.println("数据库:"+loginAdmin.getPassword());
			System.out.println( "前台:"+MD5Util.md5(admin.getPassword().trim()));
			if(  MD5Util.md5(admin.getPassword().trim()).equals(loginAdmin.getPassword()) ){
				request.getSession().setAttribute("admin",admin);
				//转到管理人员主页
				//重定向
				response.sendRedirect(request.getContextPath()+"/jsp/admin/index.jsp");
			}else{
				request.setAttribute("msg", "密码输入有误！");
				request.getRequestDispatcher("/jsp/admin/login.jsp").forward(request, response);
				return;
			}
		}else{
			request.setAttribute("msg", "用户名不存在！");
			request.getRequestDispatcher("/jsp/admin/login.jsp").forward(request, response);
			return;
		}
	}

	/**
	 * 管理员账号注册
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void register(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//得到前台的输入信息
		Admins admins = WebUtil.copyRequestToBean(request, Admins.class);
		System.out.println(admins);
		service.registerAdmins(admins);
		request.getRequestDispatcher("/jsp/admin/login.jsp").forward(request, response);
		return;
	}

}
